package org.rainwalk.bill.api.log;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.rainwalk.bill.api.model.Response;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.StringJoiner;

@Slf4j
@Aspect
@Component
@Order(999)
public class LogDelegate {

    @Around(value = "@annotation(ApiLog)")
    public Object ar(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        ApiLog apiLog = method.getAnnotation(ApiLog.class);
        String value = apiLog.value();
        log.info("接口描述： {}", value);
        Object[] args = pjp.getArgs();
        String[] argNames = signature.getParameterNames();
        StringJoiner joiner = new StringJoiner(", ");
        for (int i = 0; i < argNames.length; i++) {
            joiner.add(String.format("%s = %s", argNames[i], args[i].toString()));
        }
        log.info("接口入参：{}", joiner.toString());
        Object obj = pjp.proceed();
        log.info("接口响应 ：{}", JSONUtil.toJsonStr(obj));
        return obj;
    }


}
